<?php

/**
 * Class Core_Cli
 * @package Core
 */
class Core_Cli extends Core_Singleton {

    protected $_argv;
    protected $_cmd;
    protected $_params = array();

    protected function __construct() {
        parent::__construct();
        global $argv;
        $this->_argv = $argv;
        $this->_parseArgs($argv);
    }

    /**
     * @example
[pfisher ~]$ php test.php --foo --bar=baz
  ["foo"]   => true
  ["bar"]   => "baz"

[pfisher ~]$ php test.php -abc
  ["a"]     => true
  ["b"]     => true
  ["c"]     => true

[pfisher ~]$ php test.php arg1 arg2 arg3
  [0]       => "arg1"
  [1]       => "arg2"
  [2]       => "arg3"
     */
    protected function _parseArgs($argv) {
        array_shift($argv);
        $this->_cmd = array_shift($argv);
        $out = array();
        foreach ($argv as $arg) {
            if (substr($arg, 0, 2) == '--') {
                $eqPos = strpos($arg, '=');
                if ($eqPos === false) {
                    $key = substr($arg, 2);
                    $out[$key] = isset($out[$key]) ? $out[$key] : true;
                } else {
                    $key = substr($arg, 2, $eqPos - 2);
                    $out[$key] = substr($arg, $eqPos + 1);
                }
            } else if (substr($arg, 0, 1) == '-') {
                if (substr($arg, 2, 1) == '=') {
                    $key = substr($arg, 1, 1);
                    $out[$key] = substr($arg, 3);
                } else {
                    $chars = str_split(substr($arg, 1));
                    foreach ($chars as $char) {
                        $key = $char;
                        $out[$key] = isset($out[$key]) ? $out[$key] : true;
                    }
                }
            } else {
                $out[] = $arg;
            }
        }
        $this->_params = $out;
    }

    public function getParams() {
        return $this->_params;
    }

    public function getParam($key, $default = null) {
        if ($this->hasParam($key)) {
            return $this->_params[$key];
        } else {
            return $default;
        }
    }

    public function hasParam($key) {
        return isset($this->_params[$key]);
    }

    public function getCmd() {
        return $this->_cmd;
    }

}